package cn.edu.zime.tjh.client;

import cn.edu.zime.tjh.handler.EchoClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

public class EchoClient {
    public static final String HOST = "127.0.0.1";

    public static final int PORT = 9000;

    public EchoClient(){

    }

    public void start(){
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)  // 使用NIO传输
                    .option(ChannelOption.TCP_NODELAY, true)  // 禁用Nagle算法
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new StringDecoder());
                            p.addLast(new StringEncoder());
                            p.addLast(new EchoClientHandler());
                        }
                    });

            // 连接服务器
            ChannelFuture f = b.connect(HOST, PORT).sync();
            System.out.println("Connected to Echo server... (type 'exit' to quit)");

            // 从控制台读取输入
            Channel channel = f.channel();
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                if ("exit".equalsIgnoreCase(line)) break;
                channel.writeAndFlush(line);  // 发送消息
            }

            // 关闭连接
            channel.closeFuture().sync();
        }
        catch(InterruptedException e){
            e.printStackTrace();
        }
        finally {
            group.shutdownGracefully();
        }
    }
}
